package com.xaicode.ctoroad.kafka;

import lombok.extern.slf4j.Slf4j;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.common.protocol.types.Field;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ExecutionException;

/**
 * @author Locker cjxia@isoftstone.com
 * @version 1.0
 */
@RestController
@RequestMapping("kafka")
@Slf4j
public class KafkaController {

    private final KafkaSendHelper kafkaSendHelper;

    private final KafkaConsumer<String, String> kafkaConsumer;

    public KafkaController(KafkaSendHelper kafkaSendHelper, KafkaConsumer<String, String> kafkaConsumer) {
        this.kafkaSendHelper = kafkaSendHelper;
        this.kafkaConsumer = kafkaConsumer;
    }

    @GetMapping("send")
    @ResponseBody
    public void send(@RequestParam String topic, @RequestParam String message) {
        kafkaSendHelper.send(topic, message);
    }

    @GetMapping("topic")
    @ResponseBody
    public Set<String> createTopic(@RequestParam String topic) throws ExecutionException, InterruptedException {
        kafkaSendHelper.createTopic(topic);
        return kafkaSendHelper.listTopics();
    }

    @GetMapping("sub")
    @ResponseBody
    public Set<String> subTopic(@RequestParam List<String> topics) throws ExecutionException, InterruptedException {
        LinkedList<Map> subscribe = kafkaSendHelper.subscribe(topics);

        subscribe.stream().map(map -> {
            Object topic = map.get("topic");
            log.info("sub controller --- {}", topic);
            return "";
        });

        return kafkaSendHelper.listTopics();
    }

}
